package org.six11.ss.client;

import java.util.ArrayList;
import java.util.List;

import org.jdom.Element;
import org.six11.ss.shared.Message;
import org.six11.util.adt.MultiState;

/**
 * 
 *
 * @author Gabe Johnson <johnsogg@cmu.edu>
 */
public class ThemeOptionsMessageHandler extends AWTMessageHandler {

  /**
   * @param state
   */
  protected ThemeOptionsMessageHandler(MultiState state) {
    super(state);
  }

  /**
   * 
   */
  @SuppressWarnings("unchecked")
  @Override
  public void handleAWT(Message msg) {
    bug("Got to the theme options message handler.");
    String myCurrentChoice = "";
    List<ThemeChoice> currentChoices = (List<ThemeChoice>) state
        .getValue(ClientStateNames.K_THEME_LIST);
    bug ("I currently know about " + currentChoices.size() + " choices.");
    
    // iterate through and find which (if any) is my current choice.
    for (ThemeChoice tc : currentChoices) {
      if (tc.isMyChoice()) {
        myCurrentChoice = tc.getId();
        break;
      }
    }
    
    // reset choices based on what the server just said.
    List<ThemeChoice> newChoices = new ArrayList<ThemeChoice>();
    List options = msg.getRoot().getChildren("themeOptions");
    bug("The server tells me about " + options.size() + " options.");
    for (Object obj : options) {
      ThemeChoice tc = new ThemeChoice();
      Element elm = (Element) obj; // stupid jdom.
      tc.setId(elm.getAttributeValue("themeOptionsID"));
      tc.setName(elm.getAttributeValue("themeName"));
      tc.setVotes(elm.getAttributeValue("numVotes"));
      if(tc.getId().equals(myCurrentChoice)) {
        tc.setMyChoice(true);
      }
      newChoices.add(tc);
    }
    
    // reset the main state value. listeners will pick up on this and do what they please.
    bug("Setting the theme list with " + newChoices.size() + " choices.");
    state.setValue(ClientStateNames.K_THEME_LIST, newChoices);
  }

}
